import { ref, onMounted } from 'vue'
import { api } from '@/api/index'
import { FormType } from '@/config/const'
const {  RequestMenuAll, RequesetSubMenu, RequestMenuDelete } = api
/**
 * 菜单树
 * @returns
 */
export const useTreeMenu = () => {
    const menuTree = ref([])
    const submenu = ref([])
    const disableMenuDialog = ref(false)
    const parentId = ref(0)
    const type = ref<string>(FormType.ADD)
    const currentMenu = ref()
    const roleId = localStorage.getItem('roleId')

    const defaultProps = {
        children: 'children',
        label: 'label',
    }

    onMounted(() => {
        parentId.value = 0 // 初始化parentId为根节点
        getMenuList()
    })
    const setCheckedKeys = () => {
        // menuTreeRef.value.setCheckedKeys([parentId], false)
    }
    //事件
    const onNodeClick = (nodeObj:any) => {
        parentId.value = nodeObj.id
        RequesetSubMenu(nodeObj.id).then(data => {
            submenu.value = data.resultInfo
        })
    }
    /**
     * 获取菜单数据
     */
    const getMenuList = () => {
        RequestMenuAll()
            .then(data => {
                let { resultCode, resultInfo } = data
                if (resultCode == 1) {
                    menuTree.value = resultInfo
                    return RequesetSubMenu(resultInfo[0].id)
                }
            })
            .then(data => {
                if (data.resultCode == 1) {
                    submenu.value = data.resultInfo
                    setCheckedKeys()
                }
            })
    }
    // 弹框
    const onAddMenu = () => {
        type.value = FormType.ADD
        disableMenuDialog.value = true
    }
    // 编辑
    const onEditMenu = (row:any)=>{
        type.value = FormType.EDIT
        disableMenuDialog.value = true
        currentMenu.value = row
    }
    //删除菜单
    const onDeleteMenu = (id:number) => {
        RequestMenuDelete(roleId, id).then(data => {
            if (data.resultCode == 1) {
                getMenuList()
                ElMessage.success('删除成功!')
            }
        })
    }
    /**
     * 删除根菜单
     */
    const onDeleteRootMenu = ()=>{
        onDeleteMenu(parentId.value)
    }
    const onRefreshMenu = () => {
        getMenuList(roleId)
    }

    return {
        parentId,
        menuTree,
        defaultProps,
        submenu,
        disableMenuDialog,
        currentMenu,
        type,
        onNodeClick,
        onAddMenu,
        getMenuList,
        setCheckedKeys,
        onDeleteMenu,
        onDeleteRootMenu,
        onRefreshMenu,
        onEditMenu,
    }
}
